#include "my_stdio.h"
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

My_FILE* BuyFile(int fd,int flag)
{
    My_FILE* f=(My_FILE*)malloc(sizeof(My_FILE));
    if(!f)
        return NULL;

   f->bufferlen=0;
   f->fileno=fd;
   f->flush_method=FLUSH_NONE;
   f->flag=flag;
   memset(f->outbuffer,0,sizeof(f->outbuffer));
   return f;
}


My_FILE* myfopen(const char* path,const char* mode)
{
    int fd=-1;
    int flag=0;
    if(strcmp(mode,"w")==0)
    {
        flag=O_WRONLY|O_CREAT|O_TRUNC;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"a")==0)
    {
        flag=O_WRONLY|O_CREAT|O_APPEND;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"r")==0)
    {
        flag=O_RDONLY;
        fd=open(path,flag);
    }

    if(fd<0)
        return NULL;
    
    return BuyFile(fd,flag);
}


void myfclose(My_FILE* file)
{
    if(file->fileno<0)
        return;
    myfflush(file);
    close(file->fileno);
    free(file);
}

int myfwrite(const void* str,int num,My_FILE* file)
{
    //拷贝
    memcpy(file->outbuffer+file->bufferlen,str,num); 
    file->bufferlen+=num;
    //判断是否满足刷新条件
    if((file->flush_method & FLUSH_LINE) && file->outbuffer[file->bufferlen-1]=='\n')
    {
        myfflush(file);
    }
    
    return num;
}

void myfflush(My_FILE* file)
{
    if(file->bufferlen<=0)
        return;

    //把数据拷贝到文件缓冲区中
    int n=write(file->fileno,file->outbuffer,file->bufferlen);
    //强制将文件的内存缓冲区数据同步到磁盘
    fsync(file->fileno);
    file->bufferlen=0;
}
